# controllers/api_controller.py
from flask import jsonify, request
from controllers.user_auth import requires_auth
from services.order_service import format_phone_number, format_phone_number_without_prefix
import httpx
from config import SITES

class APIController:
    def __init__(self, app):
        self.app = app
        self.register_routes()
    
    def register_routes(self):
        """注册路由"""
        self.app.route('/api/format-phone', methods=['POST'])(self.api_format_phone)
        self.app.route('/api/format-phone-no-prefix', methods=['POST'])(self.api_format_phone_no_prefix)
        self.app.route('/api/sync-orders', methods=['POST'])(self.api_sync_orders)  # 添加手动同步路由
        self.app.route('/api/woocommerce/products', methods=['GET'])(self.api_get_woocommerce_products)  # 添加获取WooCommerce商品路由
        self.app.route('/api/woocommerce/products/<int:product_id>/variations/<int:variation_id>', methods=['GET'])(self.api_get_woocommerce_product_variation)  # 添加获取WooCommerce商品变体路由
    
    @requires_auth
    def api_format_phone(self):
        try:
            data = request.get_json()
            phone = data.get('phone', '')
            country = data.get('country', '')
            
            # 格式化手机号
            formatted_phone = format_phone_number(phone, country)
            
            return jsonify({
                'success': True,
                'original_phone': phone,
                'country': country,
                'formatted_phone': formatted_phone
            })
        except Exception as e:
            return jsonify({
                'success': False,
                'error': str(e)
            }), 400
    
    @requires_auth
    def api_format_phone_no_prefix(self):
        try:
            data = request.get_json()
            phone = data.get('phone', '')
            country = data.get('country', '')
            
            # 格式化手机号（不显示国家区号）
            formatted_phone = format_phone_number_without_prefix(phone, country)
            
            return jsonify({
                'success': True,
                'original_phone': phone,
                'country': country,
                'formatted_phone': formatted_phone
            })
        except Exception as e:
            return jsonify({
                'success': False,
                'error': str(e)
            }), 400
    
    @requires_auth
    def api_sync_orders(self):
        """手动触发订单同步"""
        try:
            # 导入同步函数
            from app import sync_all
            
            # 执行同步并获取统计信息
            sync_stats = sync_all()
            
            return jsonify({
                'success': True,
                'message': '订单同步已完成',
                'details': f'同步完成！新增 {sync_stats["inserted"]} 个订单，更新 {sync_stats["updated"]} 个订单',
                'stats': sync_stats
            })
        except ValueError as e:
            # 处理特定的值错误，如Cloudflare拦截
            error_msg = str(e)
            if "cloudflare" in error_msg.lower() or "拦截" in error_msg:
                return jsonify({
                    'success': False,
                    'error': f'同步失败：{error_msg}。这通常是由于目标站点启用了安全防护导致的，请稍后重试。'
                }), 429  # 使用429状态码表示请求过于频繁
            else:
                return jsonify({
                    'success': False,
                    'error': f'同步失败：{error_msg}'
                }), 400
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'同步过程中发生未预期的错误：{str(e)}'
            }), 500
    
    @requires_auth
    def api_get_woocommerce_products(self):
        """获取WooCommerce商品信息"""
        try:
            # 获取查询参数
            site_name = request.args.get('site', '')
            search = request.args.get('search', '')
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 20))
            
            # 查找对应的站点配置
            site_config = None
            for site in SITES:
                if site['user'] == site_name or site['domain'] == site_name:
                    site_config = site
                    break
            
            if not site_config:
                return jsonify({
                    'success': False,
                    'error': '未找到指定的站点配置'
                }), 400
            
            # 构建API请求参数
            params = {
                'per_page': min(per_page, 50),  # 限制每页最大数量
                'page': page,
                'status': 'publish'
            }
            
            # 修改搜索参数处理逻辑
            # WooCommerce API的search参数可能不适用于所有情况，我们添加更多搜索字段
            if search:
                # 尝试多种搜索方式
                # 方法1: 使用search参数
                params['search'] = search
                
                # 方法2: 如果search参数无效，尝试使用其他参数
                # params['include'] = search  # 如果search是ID列表
                
                # 注意：WooCommerce API的搜索功能可能有限制
                # 我们可以尝试使用模糊匹配或其他方式
            
            # 添加浏览器模拟的请求头
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate, br",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "none",
                "Cache-Control": "max-age=0"
            }
            
            # 发送请求到WooCommerce API
            url = f"{site_config['url']}/wp-json/wc/v3/products"
            
            print(f"请求URL: {url}")  # 调试信息
            print(f"请求参数: {params}")  # 调试信息
            
            # 使用httpx发送请求
            with httpx.Client(timeout=30.0, http2=True, follow_redirects=True, headers=headers) as client:
                response = client.get(
                    url,
                    params=params,
                    auth=(site_config["consumer_key"], site_config["consumer_secret"]),
                    headers=headers
                )
                response.raise_for_status()
                products = response.json()
            
            print(f"返回商品数量: {len(products)}")  # 调试信息
            
            # 如果搜索结果为空，尝试不使用搜索参数获取所有商品然后本地过滤
            # 修改条件判断逻辑，确保本地过滤机制能被触发
            if search and (len(products) == 0 or not products):
                print("搜索结果为空或无效，尝试获取所有商品并本地过滤")
                # 获取所有商品 - 需要重新创建client
                all_params = {
                    'per_page': min(100, per_page * 2),  # 增加获取数量以提高匹配率
                    'page': 1,  # 只获取第一页
                    'status': 'publish'
                }
                
                try:
                    # 重新创建client以避免"client has been closed"错误
                    with httpx.Client(timeout=30.0, http2=True, follow_redirects=True, headers=headers) as all_client:
                        all_response = all_client.get(
                            url,
                            params=all_params,
                            auth=(site_config["consumer_key"], site_config["consumer_secret"]),
                            headers=headers
                        )
                        all_response.raise_for_status()
                        all_products = all_response.json()
                    
                    print(f"获取到所有商品数量: {len(all_products)}")  # 调试信息
                    
                    # 本地过滤商品
                    filtered_products = []
                    search_lower = search.lower()
                    for product in all_products:
                        # 检查商品名称是否包含搜索词
                        if search_lower in product.get('name', '').lower():
                            filtered_products.append(product)
                        # 也可以检查SKU等其他字段
                        elif search_lower in str(product.get('sku', '')).lower():
                            filtered_products.append(product)
                        # 检查分类
                        elif any(search_lower in str(cat.get('name', '')).lower() for cat in product.get('categories', [])):
                            filtered_products.append(product)
                    
                    print(f"本地过滤后商品数量: {len(filtered_products)}")  # 调试信息
                    products = filtered_products
                except Exception as e:
                    print(f"获取所有商品进行本地过滤时出错: {str(e)}")
                    # 即使本地过滤出错，也返回原始搜索结果
                    pass
            
            # 处理商品数据，提取需要的信息
            processed_products = []
            for product in products:
                # 获取商品属性
                attributes = []
                for attr in product.get('attributes', []):
                    attributes.append({
                        'name': attr.get('name', ''),
                        'value': ', '.join(attr.get('options', [])) if attr.get('options') else attr.get('option', '')
                    })
                
                # 获取商品变体信息
                variations = []
                for variation in product.get('variations', []):
                    # 注意：这里我们只获取变体ID，详细信息需要另外请求
                    variations.append(variation)
                
                processed_products.append({
                    'id': product.get('id'),
                    'name': product.get('name'),
                    'sku': product.get('sku', ''),
                    'price': product.get('price'),
                    'regular_price': product.get('regular_price'),
                    'sale_price': product.get('sale_price'),
                    'stock_status': product.get('stock_status'),
                    'stock_quantity': product.get('stock_quantity'),
                    'categories': [cat.get('name') for cat in product.get('categories', [])],
                    'attributes': attributes,
                    'variations': variations,
                    'permalink': product.get('permalink')
                })
            
            print(f"处理后商品数量: {len(processed_products)}")  # 调试信息
            
            return jsonify({
                'success': True,
                'products': processed_products,
                'page': page,
                'per_page': len(processed_products)
            })
            
        except httpx.RequestError as e:
            return jsonify({
                'success': False,
                'error': f'网络请求错误: {str(e)}'
            }), 500
        except httpx.HTTPStatusError as e:
            # 特别处理403错误
            if e.response.status_code == 403:
                content_str = e.response.text.strip()
                if "cloudflare" in content_str.lower() or "just a moment" in content_str.lower():
                    return jsonify({
                        'success': False,
                        'error': '请求被Cloudflare安全防护拦截，请稍后重试或联系站点管理员'
                    }), 429
                else:
                    return jsonify({
                        'success': False,
                        'error': 'API访问被拒绝，请检查API密钥和权限设置'
                    }), 403
            else:
                return jsonify({
                    'success': False,
                    'error': f'HTTP错误: {e.response.status_code} - {e.response.text[:200]}'
                }), e.response.status_code
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'获取商品信息时出错: {str(e)}'
            }), 500

    @requires_auth
    def api_get_woocommerce_product_variation(self, product_id, variation_id):
        """获取WooCommerce商品变体信息"""
        try:
            # 获取查询参数
            site_name = request.args.get('site', '')
            
            # 查找对应的站点配置
            site_config = None
            for site in SITES:
                if site['user'] == site_name or site['domain'] == site_name:
                    site_config = site
                    break
            
            if not site_config:
                return jsonify({
                    'success': False,
                    'error': '未找到指定的站点配置'
                }), 400
            
            # 添加浏览器模拟的请求头
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate, br",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "none",
                "Cache-Control": "max-age=0"
            }
            
            # 发送请求到WooCommerce API
            url = f"{site_config['url']}/wp-json/wc/v3/products/{product_id}/variations/{variation_id}"
            
            # 使用httpx发送请求
            with httpx.Client(timeout=30.0, http2=True, follow_redirects=True, headers=headers) as client:
                response = client.get(
                    url,
                    auth=(site_config["consumer_key"], site_config["consumer_secret"]),
                    headers=headers
                )
                response.raise_for_status()
                
                # 检查是否被Cloudflare拦截
                content_str = response.text.strip()
                if "cloudflare" in content_str.lower() and ("challenge" in content_str.lower() or "just a moment" in content_str.lower()):
                    return jsonify({
                        'success': False,
                        'error': '请求被Cloudflare安全防护拦截，请稍后重试或联系站点管理员'
                    }), 429
                
                variation = response.json()
            
            # 处理变体数据，提取需要的信息
            processed_variation = {
                'id': variation.get('id'),
                'name': variation.get('name'),
                'sku': variation.get('sku', ''),
                'price': variation.get('price'),
                'regular_price': variation.get('regular_price'),
                'sale_price': variation.get('sale_price'),
                'stock_status': variation.get('stock_status'),
                'stock_quantity': variation.get('stock_quantity'),
                'attributes': variation.get('attributes', []),
                'permalink': variation.get('permalink')
            }
            
            return jsonify({
                'success': True,
                'variation': processed_variation
            })
            
        except httpx.RequestError as e:
            return jsonify({
                'success': False,
                'error': f'网络请求错误: {str(e)}'
            }), 500
        except httpx.HTTPStatusError as e:
            # 特别处理403错误
            if e.response.status_code == 403:
                content_str = e.response.text.strip()
                if "cloudflare" in content_str.lower() or "just a moment" in content_str.lower():
                    return jsonify({
                        'success': False,
                        'error': '请求被Cloudflare安全防护拦截，请稍后重试或联系站点管理员'
                    }), 429
                else:
                    return jsonify({
                        'success': False,
                        'error': 'API访问被拒绝，请检查API密钥和权限设置'
                    }), 403
            else:
                return jsonify({
                    'success': False,
                    'error': f'HTTP错误: {e.response.status_code} - {e.response.text[:200]}'
                }), e.response.status_code
        except Exception as e:
            return jsonify({
                'success': False,
                'error': f'获取商品变体信息时出错: {str(e)}'
            }), 500